/*
 * Copyright 2016-2016 the original author or authors.
 * Created on 2016/12/27 上午10:55
 */
package cn.com.geasy.base.repoisitory;

import cn.com.geasy.base.BaseEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 该工厂类使用 {@link BaseRepositoryImpl} 替代了 {@link BaseRepository} 接口的默认实现。
 *
 * @author Mechanic
 * @version 1.0
 */
public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T,
  I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new BaseRepositoryFactory(em);
    }

    private static class BaseRepositoryFactory<T extends BaseEntity, I extends Serializable>
      extends JpaRepositoryFactory {

        private final EntityManager em;

        BaseRepositoryFactory(EntityManager em) {
            super(em);
            this.em = em;
        }

        @Override
        @SuppressWarnings("unchecked")
        protected Object getTargetRepository(RepositoryInformation information) {
            //new BaseRepository<T, I>();
            return new BaseRepositoryImpl<T, I>((Class<T>) information.getDomainType(), em);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}